/*! 
 * Conversion utilities from Ogre's and PhxEngine math objects.
 *
 * \author Devis Rossini
 * \date 02 April 2012
 */
#ifndef PHXOGREUTILS_H_INCLUDE_GUARD
#define PHXOGREUTILS_H_INCLUDE_GUARD

#include <Ogre.h>
#include <PhxEngine.h>

namespace PhxOgreUtils
{
	inline phx::Vector3 PhxVector3(const Ogre::Vector3& iOgreVector)
	{
		return phx::Vector3(iOgreVector.x, iOgreVector.y, iOgreVector.z);
	}

	inline phx::Quaternion PhxQuaternion(const Ogre::Quaternion& iOgreQuaternion)
	{
		return phx::Quaternion(iOgreQuaternion.x, iOgreQuaternion.y, iOgreQuaternion.z, iOgreQuaternion.w);
	}

	inline Ogre::Vector3 OgreVector3(const phx::Vector3& iPhxVector)
	{
		return Ogre::Vector3(iPhxVector.x, iPhxVector.y, iPhxVector.z);	
	}
	
	inline Ogre::Quaternion OgreQuaternion(const phx::Quaternion& iPhxQuaternion)
	{
		return Ogre::Quaternion(iPhxQuaternion.r, iPhxQuaternion.i, iPhxQuaternion.j, iPhxQuaternion.k);	
	}

	inline void TextureToHeightField(const Ogre::String& iTextureName, phx::HeightField& oHeightField)
	{
		Ogre::TextureManager* texManager = Ogre::TextureManager::getSingletonPtr();
		Ogre::TexturePtr texPtr = texManager->load(iTextureName, "General");
		Ogre::Image im;
		texPtr->convertToImage(im);

		unsigned hfdSize = im.getWidth() * im.getHeight();
		phx::HeightFieldData hfd(hfdSize);

		for(size_t j = 0; j < im.getHeight(); ++j)
		{
			for(size_t i = 0; i < im.getWidth(); ++i)
			{
				float color = im.getColourAt(i, j, 0).r;
				phx::real height = color * 16;

				phx::HeightFieldVertex vertex;
				vertex.mVertexHeight	= height;
				vertex.mVertexMaterial	= phx::Material::DEFAULT_MATERIAL;

				hfd.at(i * im.getWidth() + j) = vertex;
			}
		}

		// TODO: Rewrite this orrible thing, plz :S
		oHeightField = phx::HeightField(im.getHeight(), im.getWidth(), hfd);
	}
}

#endif // PHXOGREUTILS_H_INCLUDE_GUARD